// 云函数入口文件
let cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
let db = cloud.database();
let _ = cloud.database().command;
exports.main = async (event, context) => {
  //调用时间回到一天前
  let timestamp = new Date().valueOf() - 86400000;
  let orderRes = "failed";
  let timeTableRes = "failed"
  //这里是删除order
  try {
    orderRes = await db.collection('order').where({
      timestamp: _.lte(timestamp)
    }).remove()
  } catch (e) {
    console.error(e)

  }
  //删除timeTable
  try {
    timeTableRes = await db.collection('timeTable').where({
      timestamp: _.lte(timestamp)
    }).remove()
  } catch (e) {
    console.error(e)
  }

  //删除云储存的图片
  let resul = await db.collection("QRcode").where({ timestamp: _.lt(timestamp) }).get()

  let data = resul.data
  let filelist = []
  let deleteResult=null
  for (let i in data) {
    filelist.push(data[i].path)
  }
  if(filelist.length!=0)
  deleteResult = await cloud.deleteFile({
    fileList: filelist
  })
  
  //删除QRcode
  let QRcodeRes = "failed"
  try {
    QRcodeRes = await db.collection('QRcode').where({
      timestamp: _.lte(timestamp)
    }).remove()
  } catch (e) {
    console.error(e)
  }

  //添加timeTable
  let k = new Date()
  let gt = k.valueOf()
  let task = []
  //lt是前一天的当前时间
  let lt = k - 86400000
  task.push(db.collection("timeTable").where({
    timestamp: _.lt(lt)
  }).remove())


  let res = await db.collection("timeTable").where({
    timestamp: _.gt(gt)
  }).orderBy("timestamp", "desc").limit(1).get()

  let list = []
  //当天的六点
  let start = k.setHours(6, 0, 0, 0).valueOf() 
  //四十五天以后的六点
  let end = start + 3888000000
  //如果存在今天以后的时间戳
  if (res.data.length != 0) {
    start = res.data[0].timestamp
    let g = new Date(start).getHours()
    if (g != 18) {
      while (g < 18) {
        //6，9，12，15，18
        g += 3
        start += 10800000
        if (start >= end) {
          break
        }
        list.push({
          isOpen: true,
          timestamp: start,
          number: 0,
          message: ""
        })
      }
    }
    //第二天六点
    start += 43200000
  }
  for (let i = 1; i < 226 && start < end; i++) {
    list.push({
      isOpen: true,
      timestamp: start,
      number: 0,
      message: ""
    })
    if (i % 5 == 0) {
      start += 43200000
    }
    else {
      start += 10800000
    }
  }

  if (list.length != 0) {
    task.push(db.collection("timeTable").add({
      data: list
    }))
  }

  let result = await Promise.all(task)
  return {
    orderDel: orderRes,
    timeTableDel: timeTableRes,
    timeTableAdd: result,
    QRcodeDel: QRcodeRes,
    storeDel: deleteResult
  }
}